<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/5/25/025
 * Time: 14:13
 */
namespace app\backend\controller;
use app\backend\controller\traits\AuthManager;
use app\backend\model\Building;
use app\backend\model\Lease;
use app\backend\model\Member;
use app\backend\model\TradeRecord;
use think\Controller;
use think\Exception;

class TradeRecordController extends Controller
{
    use AuthManager;
    private $_memberId = null;
    private $_dtype    = null;
    private $_pdtype   = null;
    private $_pmid     = null;
    private $_allAuth  = [];
    public function __construct()
    {
        parent::__construct();
        $memberInfo = $this->getLoginInfo();
        $this->_memberId = $memberInfo['mid'];
        $this->_dtype    = $memberInfo['dtype'];
        $this->_pdtype   = $memberInfo['p_dtype'];
        $this->_pmid     = $memberInfo['p_mid'];
        $this->_allAuth  = $this->getPower($this->_memberId, $this->_dtype);
    }

    /**
     * 获取交易记录列表
     * @date   2017-05-26
     * @author wuhao
     *
     * @param  string   $beginTime   开始时间
     * @param  string   $endTime     截止时间
     * @param  int      $feeType      费用类型  0=全部 1房租，2物业，3水，4电,  5公摊水，6公摊电, 7税费, 8其他费用
     * @param  float    $moneyFrom    金额上限
     * @param  float    $moneyTo      金额下限
     * @param  int      $buildingId  楼宇id
     * @param  int      $key         搜索类型  1=对方名称 2=房号
     * @param  int      $value       搜索内容
     * @param  int      $payType     支付类型 0=全部 2通联支付宝，3通联微信, 4提现  5富友
     * @param  int      $page        页数
     * @param  int      $pageSize    每页个数
     * @param  int      $excel       是否导出
     *
     * @return json
     */
    public function getList()
    {
        $code = 200;
        $msg  = '查询成功';
        try {
            $beginTime = I('begin_time');
            $endTime   = I('end_time');
            $feeType   = I('fee_type', 0, 'intval');
            $moneyFrom = I('money_from', '');
            $moneyTo   = I('money_to', '');
            $key       = I('key', 1, 'intval');
            $value     = I('value', '', 'strval');
            $buildingId = I('building_id', '', 'intval');
            $payType   = I('pay_type', 0, 'intval');
            $page      = I('page', 1, 'intval');
            $pageSize  = I('page_size', 15, 'intval');
            $excel     = I('excel', '0', 'intval');

            //$beginTime='2017-04-01';$endTime='2017-05-26';
            //$excel=1;
            //$feeType=0;$key=1;$value='金';
            if (!$beginTime || !$endTime || (!strtotime($beginTime) && !strtotime($endTime))) {
                throw new Exception('时间不能为空', 400);
            }
            if (!in_array($feeType, [0,1,2,3,4,5,6,7,8, 10, 11])) {
                throw new Exception('费用类型有误', 400);
            }
            if (!in_array($key, [1,2])) {
                throw new Exception('搜索类型有误', 400);
            }
            if (!in_array($payType, [0,2,3,4,5])) {
                throw new Exception('支付类型有误', 400);
            }
            if ($moneyFrom != '' && $moneyTo != '' && (!is_numeric($moneyFrom) || !is_numeric($moneyTo))) {
                throw new Exception('输入金额有误', 400);
            }
            $memberModel = new Member();
            $leaseModel  = new Lease();
            //$otherSide = $orderNumber = $otherBuild =  false; //不使用对应的条件
            if ($key && $value) {
                if ($key == 1) {//对方名称
                    $orderNumber = false;//不使用 对应房号去搜索的合同编号数组的条件
                    $memberInfo = $memberModel->getMemberInfo(['nickname' => ['like', "%$value%"]], 'id');
                    $otherSide = array_column($memberInfo, 'id');
                } elseif ($key == 2) {//房号
                    $otherSide = false;
                    $leaseInfo = $leaseModel->getLeaseExtByRoom($value, 'ordernum, house_number, room');
                    $orderNumber = array_column($leaseInfo, 'ordernum');
                }
            } else {
                $otherSide = $orderNumber = false;
            }

            $beginTime .= ' 00:00:00';
            $endTime   .= ' 23:59:59';

            $tradeModel = new TradeRecord();
            if ($excel == 1) {
                $data = $tradeModel->getTradeRecord($this->_pmid, $beginTime, $endTime, $feeType, $moneyFrom, $moneyTo, $payType,
                    $buildingId, $otherSide, $orderNumber, $page, $pageSize, true);
            } else {
                $data = $tradeModel->getTradeRecord($this->_pmid, $beginTime, $endTime, $feeType, $moneyFrom, $moneyTo, $payType,
                    $buildingId, $otherSide, $orderNumber, $page, $pageSize, false);
            }
            if (!$data) {
                throw new Exception('暂无数据', 201);
            }

            $ordernumArr = array_unique(array_column($data, 'ordernum'));//订单号数组
            $fromId = array_unique(array_column($data, 'from_id'));//交易对象数组

            //查询对应的房号信息
            $roomInfo = $leaseModel->getLeaseExtByOrderNum($ordernumArr, 'ordernum, house_number, room');
            //查询对应楼宇信息
            $buildId = $leaseModel->getLeaseByOrderNum($ordernumArr, 'ordernum, building_id');
            if ($buildId) {
                $buildingIdArr = array_unique(array_column($buildId, 'building_id'));
                $buildModel = new Building();
                $buildInfo = $buildModel->getBuildingList(['id' => ['in', $buildingIdArr]], 'id, name');
            } else {
                $buildId = $buildInfo = [];
            }
            //var_dump($buildId);die;

            //查询对方账号信息
            $fromMember = $memberModel->getMemberInfoById($fromId, 'id, nickname');

            foreach ($data as $a => $b) {
                //交易时间转化
                $data[$a]['rectime'] = date('Y-m-d H:i:s', $b['rectime']);
                //支出，存为负值   转为元
                $data[$a]['dmoney'] = ($b['action'] == 1) ? (yuan($b['dmoney'] * (-1))) : yuan($b['dmoney']);

                $data[$a]['building_id'] = $data[$a]['room'] = $data[$a]['building_name']  = $data[$a]['from_name'] = '';
                foreach ($roomInfo as $r) {//获取房号信息
                    if ($r['ordernum'] == $b['ordernum']) {
                        $data[$a]['room'] = $r['room'];
                        break;
                    }
                }
                foreach ($buildId as $bd) {//楼宇id信息
                    if ($bd['ordernum'] == $b['ordernum']) {
                        $data[$a]['building_id'] = $bd['building_id'];
                        break;
                    }
                }
                foreach ($buildInfo as $build) {//楼宇名称信息
                    if ($data[$a]['building_id'] == $build['id']) {
                        $data[$a]['building_name'] = $build['name'];
                        break;
                    }
                }
                foreach ($fromMember as $fm) {//对方账号信息
                    if ($fm['id'] == $b['from_id']) {
                        $data[$a]['from_name'] = $fm['nickname'];
                    }
                }
            }

            if ($excel ==1) {//导出
                $this->_exportTradeData($data);
            } else {//否则返回前端
                $sum   = $tradeModel->cntTradeRecord($this->_pmid, $beginTime, $endTime, $feeType, $moneyFrom, $moneyTo, $payType,
                    $buildingId, $otherSide, $orderNumber);
                $total = ceil($sum / $pageSize);
                $res   = [
                    'list'  => $data,
                    'total' => $total
                ];
                $this->apiReturn($code, $res, $msg);
            }
        } catch (Exception $e) {
            $code = $e->getCode();
            $msg  = $e->getMessage();
            $this->apiReturn($code, [], $msg);
        }
    }

    /**
     * 交易记录的导出
     * @date   2017-05-26
     * @author wuhao
     *
     * @param  array   $data      导出的数据
     * @param  string  $fileName  文件的名称
     */
    private function _exportTradeData($data, $fileName = '')
    {
        if (!$fileName) {
            $fileName = date('Ymd').'_交易记录统计';
        }
        if (!$data) {
            $this->apiReturn(200, [], '没有数据');
        }
        $objPHPExcel = load_excel();
        $objWriter   = new \PHPExcel_Writer_Excel5($objPHPExcel);
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->setTitle($fileName);
        $width = [
            'A' => 15,
            'B' => 15,
            'C' => 25,
            'D' => 25,
            'E' => 15,
            'F' => 15,
            'G' => 25,
            'H' => 25,
            'I' => 25,
        ];
        foreach ($width as $key => $val) {
            $objPHPExcel->getActiveSheet()->getColumnDimension($key)->setWidth($val);
        }

        $title = [
            'A1' => '楼宇名称',
            'B1' => '房号',
            'C1' => '交易时间',
            'D1' => '交易对象',
            'E1' => '交易金额',
            'F1' => '交易方式',
            'G1' => '交易流水',
            'H1' => '费用类型',
            'I1' => '账单周期',
        ];
        foreach ($title as $k => $v) {
            $objPHPExcel->getActiveSheet()->setCellValue($k, $v);
        }
        $moneyType = load_config('types', 'money_type');//金额类型
        $payType   = load_config('type', 'pay_type');   //交易方式
        $num = 1;
        foreach ($data as $key => $value) {
            ++$num;
            $objPHPExcel->getActiveSheet()->setCellValue('A'.$num, $value['building_name']);
            $objPHPExcel->getActiveSheet()->setCellValue('B'.$num, $value['room']);
            $objPHPExcel->getActiveSheet()->setCellValue('C'.$num, $value['rectime']);
            $objPHPExcel->getActiveSheet()->setCellValue('D'.$num, $value['from_name']);
            $objPHPExcel->getActiveSheet()->setCellValue('E'.$num, $value['dmoney']);
            $objPHPExcel->getActiveSheet()->setCellValue('F'.$num, $payType[$value['type']]);
            $objPHPExcel->getActiveSheet()->setCellValue('G'.$num, '`'.$value['trade_no']);
            $objPHPExcel->getActiveSheet()->setCellValue('H'.$num, $moneyType[$value['mtype']]);
            $objPHPExcel->getActiveSheet()->setCellValue('I'.$num, $value['begin_cycle'].'~'.$value['end_cycle']);
        }

        ob_end_clean();
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");;
        header('Content-Disposition:attachment;filename='.$fileName.'.xls');
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
    }
}